package zzu.mxd.answer.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import zzu.mxd.answer.entity.Student;
import zzu.mxd.answer.service.IStudentService;
import zzu.mxd.answer.vo.RecordExtend;
import zzu.mxd.common.PageRequest;
import zzu.mxd.common.R;
import zzu.mxd.utils.RedisUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 学生表 前端控制器
 * </p>
 *
 * @author mxd
 * @since 2018-11-08
 */
@Api(tags = "学生管理")
@RestController
@RequestMapping("/answer/student")
public class StudentController {
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private IStudentService studentService;
    @Value("${spring.security.sessionOutMinutes}")
    public long sessionOutMinutes;

    /**
     * 测试通过
     *
     * @param id
     * @return
     */
    @ApiOperation("查询单个学生")
    @GetMapping("/{id}")
    public R<Student> get(@ApiParam("学生ID") @PathVariable(name = "id") String id) {
        Student student = studentService.getById(id);
        return R.succC(student);
    }

    /**
     * 测试通过
     *
     * @param student
     * @return
     */
    @ApiOperation("添加学生")
    @PostMapping()
    public R<String> add(@RequestBody Student student) {
        studentService.save(student);
        return R.succ();
    }

    @ApiOperation("删除学生")
    @DeleteMapping("/{id}")
    public R<String> delete(@ApiParam(value = "学生ID") @PathVariable String id) {
        studentService.deleteFalsely(id);//假删除
        return R.succ();
    }

    @ApiOperation("分页条件查询")
    @GetMapping("/selectAll")
    public R<IPage<Student>> selectPage(PageRequest request, Student student) {
        Page<Student> page = new Page<>(request.getCurrent(), request.getSize());
        page = (Page<Student>) studentService.page(page, new QueryWrapper<>(student));
        return R.succC(page);
    }

    /**
     * 逻辑：从redis中取出并匹配verifycode
     *
     * @param id           学生ID
     * @param password     密码
     * @param verification 验证码
     * @param verifyKey    验证码key：verifyCode+学号
     * @return 0 登陆成功
     * 1 验证码错误
     * 2 用户名不存在
     * 3 用户密码错误
     * 4 用户被冻结
     * 5 异常，登陆失败
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public R<String> login(String id, String password, String verification, String verifyKey, HttpServletRequest request) {
        switch (studentService.login(id, password, verification, verifyKey)) {
            case 0:
                //返回Token
                String token = UUID.randomUUID().toString();
                redisUtils.set(id + "token", token, sessionOutMinutes, TimeUnit.MINUTES);
                redisUtils.set(id + "openId", request.getAttribute("openId").toString(), sessionOutMinutes, TimeUnit.MINUTES);
                return R.succM(token);
            case 1:
                return R.errM(1, "验证码错误");
            case 2:
                return R.errM(2, "用户名不存在");
            case 3:
                return R.errM(3, "密码错误");
            case 4:
                return R.errM(4, "用户被冻结");
            case 5:
                return R.errM(5, "服务器异常，登陆失败");


        }

        return R.errM("登录失败");
    }

    /**
     * @param id
     * @param oldPassword
     * @param newPassword
     * @param renewPassword
     * @return
     */
    @ApiOperation("修改密码")
    @PostMapping("/updatePassword")
    public R<String> updatePassword(String id, String oldPassword, String newPassword, String renewPassword) {
        if (studentService.updatePassword(id, oldPassword, newPassword, renewPassword)) {
            return R.succ();
        }
        return R.errM("操作失败");
    }

    @ApiOperation("修改学生信息")
    @PutMapping()
    public R<String> update(Student student) {
        studentService.updateById(student);
        return R.succ();
    }

    @ApiOperation("根据身份证号查询学生")
    @GetMapping("/selectByIdCard")
    public R<Student> selectByIdCard(String idCard) {
        Student student = studentService.selectByIdCard(idCard);
        return R.succC(student);
    }

    @ApiOperation("根据学生id和isRight查询学生答过的题目")
    @PostMapping("/{id}")
    public R<List<RecordExtend>> getUserExercise(@ApiParam(value = "学生ID") @PathVariable String id, @ApiParam(value = "是否正确，不传则全部，0为正确，1为错误") @RequestParam(value = "isRight", required = false) Integer isRight) {
        return R.succC(studentService.getUserExercise(id, isRight));
    }
}
